<?php
require_once '../func/db.class.php';
require_once '../func/auth.php';
require_once '../func/utils.php';

session_start();
header('Content-Type: application/json');

// 检查是否登录
if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$input = json_decode(file_get_contents("php://input"), true);
$oldPwd = $input['old_password'] ?? '';
$newPwd = $input['new_password'] ?? '';

if (!$oldPwd || !$newPwd) {
    echo json_encode(['success' => false, 'message' => '密码不能为空']);
    exit;
}
if (strlen($newPwd) < 6) {
    echo json_encode(['success' => false, 'message' => '密码长度不足6位']);
    exit;
}


$db = new Db();
$userId = getCurrentUserId();

// 获取当前用户的密码哈希
$user = $db->query("SELECT password FROM users WHERE id = ?", [$userId]);
if (!$user) {
    echo json_encode(['success' => false, 'message' => '用户不存在']);
    exit;
}

$hash = $user[0]['password'];
if (!password_verify($oldPwd, $hash)) {
    echo json_encode(['success' => false, 'message' => '原密码错误']);
    exit;
}

// 更新密码（使用 password_hash 重新加密）
$newHash = password_hash($newPwd, PASSWORD_DEFAULT);
$db->update('users', ['password' => $newHash], ['id' => $userId]);

echo json_encode(['success' => true, 'message' => '密码修改成功']);
